<?php
/**
 * Created by PhpStorm.
 * User: YF
 * Date: 2017/2/8
 * Time: 11:51
 */

namespace App\Controller;


use App\Model\Queue;
use App\Model\TaskBean;
use App\Task;
use App\Utility\Db\Redis;
use App\Utility\MyConfInfo;
use App\Utility\SysConst;
use Core\AbstractInterface\AbstractController;
use Core\Component\Di;
use Core\Component\ShareMemory;
use Core\Http\Message\Status;
use Core\Swoole\AsyncTaskManager;
use Core\Swoole\Server;
use Core\UrlParser;

class Index extends AbstractController
{
    function index()
    {
        // TODO: Implement index() method.
        $this->response()->withHeader("Content-type", "text/html;charset=utf-8");
        $this->response()->write('
    <style type="text/css">
       *{ padding: 0; margin: 0; }
       div{ padding: 4px 48px;}
       body{ background: #fff; font-family: "微软雅黑"; color: #333;font-size:24px}
       h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; }
       p{ line-height: 1.8em; font-size: 36px } a,a:hover{color:blue;}
    </style>
    <div style="padding: 24px 48px;">
        <h1>:)</h1><p>欢迎使用<b> easySwoole</b></p> 
        <span style="font-size:25px">从未如此之快 - 专为API而生的常驻内存型框架</span>
       <br/>
       <span style="font-size:20px">[ 欢迎前往 <a href="https://github.com/kiss291323003/easyswoole/" target="easySwoole">GitHub</a> 为 easySwoole 赏一个Star ]</span>
   </div>
 ');/*  url:domain/index.html  domain/   domain  */
    }

    function onRequest($actionName)
    {
        // TODO: Implement onRequest() method.
    }

    function actionNotFound($actionName = null, $arguments = null)
    {
        // TODO: Implement actionNotFount() method.
        $this->response()->withStatus(Status::CODE_NOT_FOUND);
        $this->response()->write(file_get_contents(ROOT . "/App/Static/404.html"));
    }

    function afterAction()
    {
        // TODO: Implement afterResponse() method.
    }

    function test()
    {
//        $db = Di::getInstance()->get(SysConst::MYSQL);
//        $packageList = $db->select('package_id,ship_code')->where('print_label = ""')->from('ueb_order_package');
        var_dump('test');
        $this->response()->writeJson(200, null, 'test');
    }

    function test2()
    {
        Di::getInstance()->set('test2', function () {
            return 'test222';
        });

        $test2 = Di::getInstance()->get('test2');
        var_dump($test2);
        $this->response()->write("this is test2");
    }

    function test3()
    {
        $this->response()->write("this is test2");
    }

    function shutdown()
    {
        Server::getInstance()->getServer()->shutdown();
    }

    function router()
    {
        $this->response()->write("your router not end");
    }

    function addTask()
    {
        $url = $this->request()->getRequestParam("url");
        if (empty($url)) {
            $url = 'http://wiki.swoole.com/';
        }
        $bean = new TaskBean();
        for ($i = 1; $i <= 200; $i++) {
            $bean->setUrl($url);
            //做异步投递
            AsyncTaskManager::getInstance()->add(function () use ($bean) {
                Queue::set($bean);
            });
        }
        $this->response()->writeJson(200, null, "任务投递成功");
    }

    public function addTaskNew()
    {
        $db = Di::getInstance()->get(SysConst::MYSQL);
        $packageList = $db->select('package_id,ship_code')
            ->where('print_label = ""')
            ->limit(50)
            ->from('ueb_order_package');
        $temp = array();
        if ($packageList) {
            foreach ($packageList as $package) {
                $temp[$package['ship_code']][] = $package['package_id'];
            }
            if (count($temp)) {
                //做异步投递
                AsyncTaskManager::getInstance()->add(function () use ($temp) {
                    foreach ($temp as $key => $val) {
                        Queue::setTask($key, serialize($val));
                    }
                });
            }
        }
        $this->response()->writeJson(200, null, "任务投递成功,TaskNum" . count($temp));
    }

    public function addTaskByConfig()
    {
        $task = $this->request()->getRequestParam('task');
        $taskInfo = MyConfInfo::getInstance()->getConfig('task_info');
        if ($taskInfo) {
            //做异步投递
            AsyncTaskManager::getInstance()->add(function () use ($taskInfo) {
                foreach ($taskInfo as $val) {
                    Queue::setTask($val['task_name'], serialize($val));
                }
            });
        }
        $this->response()->writeJson(200, null, "任务投递成功,TaskNum" . count($taskInfo));
    }

    public function status()
    {
        $num = ShareMemory::getInstance()->get(SysConst::TASK_RUNNING_NUM);
        $servStats = Server::getInstance()->getServer()->stats();
        $test = 2;
        isset($servStats['start_time']) && $servStats['start_time_info'] = date('Y-m-d H:i:s', $servStats['start_time']);
        //获取当前的任务状态
        $redis = Redis::getInstance();
        $taskList = $redis->hGetAll(Queue::QUEUE_NAME);
        $runTaskList = $redis->hGetAll(Queue::QUEUE_RUNNING_NAME);
        $this->response()->writeJson(200, array(
            "taskRuningNum" => $num,
            'serverStats' => $servStats,
            'test' => $test,
            'taskList' => $taskList,
            'runTaskList' => $runTaskList
        ));
    }

    public function info()
    {
        ob_start();
        phpinfo();
        $str = ob_get_contents();
        ob_end_clean();
        $this->response()->write($str);
    }

    public function reload()
    {
        Server::getInstance()->getServer()->reload();
    }

    public function setConfig()
    {
        $data = array(
            'run_task_switch' => 1,
            'run_task_num' => 1,
            'task_info' => array(
                array(
                    'task_name' => 'wh_track',
                    'task_bean' => 'wh',
                    'task_thread' => 5,
                    'task_thread_return' => 'package_return_list',
                    'task_run_time' => ''
                ),
                array(
                    'task_name' => 'ali_track',
                    'task_bean' => '',
                    'task_thread' => 1,
                    'task_run_time' => ''
                )
            )
        );
        MyConfInfo::getInstance()->setConfig($data);
        $configInfo = MyConfInfo::getInstance()->getConfig();
        $this->response()->writeJson(200, $configInfo, '设置成功');
    }
}